<?php

class Query_filter {
	private $session_key = null;
	private $session = true;
	private $_offset = 0;
	private $_limit = 10;
	
	/**
	 * 
	 * @param String $session_key
	 * @param Boolean $session - if keep the state in $_SESSION
	 * @param Integer $limit
	 */
	public function __construct($session_key = null, $session = true, $limit = null, $offset = null) {
		$this->session = $session;
		
		if ($this->session) {
			if (!$session_key) {
				$session_key = str_replace('/', '_', ROUTE) . '_query_filter';
			}
			
			if (!isset($_SESSION[$session_key]) || isset($_GET['filter_reset'])) {
				$_SESSION[$session_key] = array();
			}
			$this->session_key = $session_key;
		}
		
		//init
		$page = (int) $this->get('page', 1);
		if ($page < 1) $page = 1;
		$this->_limit = $limit ? $limit : C('config_admin_limit');
		$this->_offset = $offset ? $offset : ($page - 1) * $this->_limit;
		
		if ($this->session) {
			$GLOBALS['_PAGE'] = $page;
			$GLOBALS['_SORT'] = $this->get('sort');
			$GLOBALS['_ORDER'] = $this->get('order', 'ASC');
		}
	}
	
	/**
	 * 
	 * @param string $key
	 * @param mix $val
	 */
	public function set($key, $val) {
		$_GET[$key] = $val;
	}
	
	/**
	 * 
	 * @param string $key
	 * @param mix $default
	 * @return mix
	 */
	public function get($key, $default = null) {
		if (!$this->session) {
			return isset($_GET[$key]) ? $_GET[$key] : $default;
		}
		
		if (isset($_GET[$key])) {
			$_SESSION[$this->session_key][$key] = $_GET[$key];
		}
		if (isset($_SESSION[$this->session_key][$key])) {
			return $_SESSION[$this->session_key][$key];
		}
		else return $default;
	}
			
	public function sort($default, $order = 'ASC') {
		return ' ORDER BY ' . $this->get('sort', $default) . ' ' . $this->get('order', $order);
	}
	
	public function limit() {
		return ' LIMIT ' . $this->_offset . ', ' . $this->_limit;
	}
}